package com.china.springServer.listener;

import com.china.springServer.service.ServiceChangeListener;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.CuratorCache;
import org.apache.curator.framework.recipes.cache.CuratorCacheListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @fileName: ZookeeperServicelistener
 * @author: LmR
 * @createDate: 2023/10/21 22:18
 * @Desc:
 */
@Component
public class ZookeeperServiceListener {

    private String ZK_REGISTRY_PATH = "/mySpringServer";

    @Autowired
    private CuratorFramework curatorClient;

    private CuratorCache curatorCache;

    @PostConstruct
    public void init() throws Exception {
        curatorCache = CuratorCache.builder(curatorClient, ZK_REGISTRY_PATH).build();
        curatorCache.start();
    }

    @PreDestroy
    public void close() throws Exception {
        curatorCache.close();
    }

    public void watchServices(ServiceChangeListener listener) throws Exception {
        /**
         * Return the listener container so that listeners can be registered to be notified of changes to the cache
         *
         * 获取一个监听器，当缓存发生变化时会通知监听器触发动作
         * 可以实现对服务上线和下线的实时监听功能
         *   事件会返回
         *      ZK节点变更类型：create change delete
         *      旧数据
         *      新数据
         */
        curatorCache.listenable().addListener((type, oldData, data) -> {
            if (type == CuratorCacheListener.Type.NODE_CREATED) {
                // 服务上线注册
                String serviceAddress = new String(data.getData());
                listener.onServiceAdded(serviceAddress);
            } else if (type == CuratorCacheListener.Type.NODE_DELETED) {
                // 服务下线
                String serviceAddress = new String(data.getData());
                listener.onServiceRemoved(serviceAddress);
            }
        });

    }

}
